package com.grandbroad.eim.ui.activities;

import android.annotation.TargetApi;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.base.bean.ResultBean;
import com.easy.west.westclient.api.login.bean.ReturenUser;
import com.easy.west.westclient.api.login.bean.User;
import com.easy.west.westclient.api.login.event.GetPublicKeyEvent;
import com.easy.west.westclient.api.login.event.LoginEvent;
import com.easy.west.westclient.api.login.event.UpdateUserNameEvent;
import com.grandbroad.eim.R;
import com.grandbroad.eim.app.MyApplication;
import com.grandbroad.eim.base.BaseActivity;
import com.grandbroad.eim.entry.WechatLoginEvent;
import com.grandbroad.eim.entry.WhcatBean;
import com.grandbroad.eim.event.PhoneDispatchEvent;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.Macher;
import com.grandbroad.eim.utils.RSAUtils;
import com.grandbroad.eim.utils.ToastUtils;
import com.grandbroad.eim.wxapi.WXEntryActivity;
import com.orhanobut.hawk.Hawk;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.options.RegisterOptionalUserInfo;
import cn.jpush.im.api.BasicCallback;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.img_back_btn)
    ImageView imgBackBtn;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.edit_phone_input)
    EditText editPhoneInput;
    @BindView(R.id.tv_phone_state)
    TextView tvPhoneState;
    @BindView(R.id.edit_password_input)
    EditText editPasswordInput;
    @BindView(R.id.tv_password_state)
    TextView tvPasswordState;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.btn_wechat_login)
    CardView btnWechatLogin;
    private boolean issee =false;
    private String phone_state="手机号码格式错误";
    private String password_state="账号或密码错误";
    private String phone;
    private String password;
    private ReturenUser user;


    @Override
    protected void initview() {
        //设置点击事件
        initsession();
    }

    /**
     * 微信
     */
    private void loginToWeiXin(){
        IWXAPI mApi = WXAPIFactory.createWXAPI(this, MyApplication.WX_ID, true);
        mApi.registerApp(MyApplication.WX_ID);

        if (mApi != null && mApi.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test_neng";
            mApi.sendReq(req);
        } else
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
    }
    private void initsession() {
        //微信登陆
        btnWechatLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginToWeiXin();

            }
        });
        //注册
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(RegisterActivity.class,false);
            }
        });
        //点击登陆
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            phone = editPhoneInput.getText().toString();
            password = editPasswordInput.getText().toString();
                if (TextUtils.isEmpty(phone))
                {
                    //设置提示语
                    tvPhoneState.setVisibility(View.VISIBLE);
                    tvPhoneState.setText("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(password))
                {
                    tvPasswordState.setVisibility(View.VISIBLE);
                    tvPasswordState.setText("请输入密码");
                    return;
                }
                //请求公钥
                MyApplication.getMoleclient().getPublickey(phone);
                showProgessDialog("登陆中");
            }

        });
        //密码输入
        editPasswordInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>=1)
                {
                    tvPasswordState.setText(password_state);
                    tvPasswordState.setVisibility(View.GONE);
                }
            }
        });
        editPhoneInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String s = editPhoneInput.getText().toString();
                if (s.length()>=11)
                {
                    //验证
                    //因为是边输入边验证 从11位开始
                    boolean isphone = Macher.isPhone(s);
                    if (!isphone)
                    {
                        tvPhoneState.setText(phone_state);
                        tvPhoneState.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        tvPhoneState.setVisibility(View.GONE);
                    }
                }
                else
                {
                    tvPhoneState.setText(phone_state);
                    tvPhoneState.setVisibility(View.GONE);
                }
            }
        });
        //手机号输入
        editPhoneInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>=11)
                {
                    //验证
                    //因为是边输入边验证 从11位开始
                    boolean isphone = Macher.isPhone(s.toString());
                    if (!isphone)
                    {
                        tvPhoneState.setText(phone_state);
                        tvPhoneState.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        tvPhoneState.setVisibility(View.GONE);
                    }
                }
                else
                {
                    tvPhoneState.setText(phone_state);
                    tvPhoneState.setVisibility(View.GONE);
                }
            }
        });
        //退出
         imgBackBtn.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 finish();
             }
         });
        //设置右边edittext点击事件图标
        editPasswordInput.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //获取drawable,右边的
                //Drawable drawable_emmm = editPasswordInput.getCompoundDrawables()[2];
                switch (event.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        //只看按下
                            if (event.getX() > editPasswordInput.getWidth() - editPasswordInput.getCompoundDrawables()[2].getBounds().width()) {
                                setEditPasswordState(false);
                                if (!issee) {
                                    Log.d("lyb", "444");
                                    //点击之后执行的事件
                                    //执行对应逻辑,读取图片资源
                                    Drawable drawable_see = getResources().getDrawable(R.drawable.icon_password_visual);
                                    drawable_see.setBounds(0, 0, drawable_see.getIntrinsicWidth(), drawable_see.getIntrinsicHeight());
                                    //替换
                                    editPasswordInput.setCompoundDrawables(null,null,drawable_see,null);
                                    //设置edit样式
                                    editPasswordInput.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                                    editPasswordInput.setSelection(editPasswordInput.getText().toString()==null?0:editPasswordInput.getText().toString().length());
                                    //重绘
                                    editPasswordInput.postInvalidate();
                                    setEditPasswordState(true);
                                    issee=true;
                                    return true;
                                }
                                else {
                                    if (event.getX() > editPasswordInput.getWidth() - editPasswordInput.getCompoundDrawables()[2].getBounds().width()) {
                                        Log.d("lyb", "444");
                                        //点击之后执行的事件
                                        //执行对应逻辑,读取图片资源
                                        Drawable drawable_see = getResources().getDrawable(R.drawable.icon_login_password_hide);
                                        drawable_see.setBounds(0, 0, drawable_see.getIntrinsicWidth(), drawable_see.getIntrinsicHeight());
                                        //替换
                                        editPasswordInput.setCompoundDrawables(null,null,drawable_see,null);
                                        editPasswordInput.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                                        editPasswordInput.setSelection(editPasswordInput.getText().toString()==null?0:editPasswordInput.getText().toString().length());
                                        //重绘
                                        editPasswordInput.postInvalidate();
                                        setEditPasswordState(true);
                                        issee=false;
                                        return true;
                                }
                                }
                            }

                        break;
                }


                return false;
            }
        });
    }

    public void setEditPasswordState(boolean state)
    {
        editPasswordInput.setFocusable(state);
        editPasswordInput.setFocusableInTouchMode(state);
    }

    @Override
    protected void initdata() {
        if (getIntent().getExtras()!=null)
        {
            Bundle b = getIntent().getExtras();
            phone = b.getString("phone",null);
            if (!TextUtils.isEmpty(phone))
            {
                editPhoneInput.setText(phone);
            }
        }
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_login;
    }

    /***
     * 获取公钥
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getpublickey(GetPublicKeyEvent eva)
    {
        if (eva.isOk())
        {
            ResultBean resultBean = eva.getBean();
            if (resultBean.getStatus()==1)
            {
                String p_key = resultBean.getData().toString();
                //加密
                try {
                    RSAPublicKey key = RSAUtils.getPublicKey(p_key);
                    Log.e("22",key.toString());
                    String format_pwd = RSAUtils.publicEncrypt(password,key);
                    //没问题请求
                    MyApplication.getMoleclient().login(phone,format_pwd);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                    dissmissDialog();
                } catch (InvalidKeySpecException e) {
                    e.printStackTrace();
                    dissmissDialog();
                }
            }
            else
            {
                tvPhoneState.setText(resultBean.getErrorDescrip());
                tvPhoneState.setVisibility(View.VISIBLE);
                dissmissDialog();
            }
        }
    }

    /**
     * 登陆回调
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void login(LoginEvent eva)
    {
        if (eva.isOk())
        {
            dissmissDialog();
            user = eva.getBean();
            if (user.getStatus()==1)
            {
                //请求极光后台进行登陆或注册
                LoginIm();
                CacheUtils.saveUser(user.getData());
                startActivity(HomeActivity.class,true);
            }
            else
            {
                tvPasswordState.setVisibility(View.VISIBLE);
                tvPasswordState.setText(password_state);
                dissmissDialog();
            }
            dissmissDialog();
        }
        else
        {

            dissmissDialog();
        }

    }

    /**
     * 获取公钥
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPhone(PhoneDispatchEvent event)
    {
        editPhoneInput.setText(event.getPhone());
    }

    /**
     * 微信登陆成功的回调
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void WechatLogin(WechatLoginEvent eva)
    {
        user = eva.getWhcatBean();
        //查看自己的资料是否为空
        User mole_user = CacheUtils.getUser();
        if (mole_user.getName()==null)
        {
            WhcatBean whcatBean = Hawk.get("wechat");
            //同步资料
            MyApplication.getMoleclient().updateUsername(whcatBean.getNickname(),user.getData().getAccess_token());
            return;
        }
        showProgessDialog("登陆中");
        LoginIm() ;
    }

    /**
     * 修改用户名
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void AvatorUpload(UpdateUserNameEvent eva)
    {
        if (eva.isOk())
        {
            User r = eva.getBean();
            if (r!=null)
            {
                showProgessDialog("登陆中");
                LoginIm() ;
            }
            else
            {
                ToastUtils.show("微信登陆失败");
                dissmissDialog();
            }
        }
        else
        {
            ToastUtils.show("微信登陆失败");
            dissmissDialog();
        }
    }
    /***
     * IM登录状态的检查
     */
    private void LoginIm() {
        //这个地方如果是微信登陆密码是为空的
        //难统一所以对于拉流端用户统一采用，，asd123
        JMessageClient.login(user.getData().getAccess_token(), "asd123",
                new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        Log.e("登录信息", i + ":" + s);
                        if (i == 0) {
                            dissmissDialog();
                            //设置别名
                            //1.当前域
                            //2.用户序列号(相当于key)
                            //3.别名为user的token
                            //这里是推送相关，暂时不考虑
                            //JPushInterface.setAlias(getApplicationContext(), user.getData().getId(), user.getData().getAccess_token());
                                //0即登录成功
                            dissmissDialog();
                            startActivity(HomeActivity.class, true);
                        } else {
                            switch (i) {
                                case 871303:
                                    //用户名错误
                                    ToastUtils.show("您的用户名错误");
                                    dissmissDialog();
                                    break;
                                case 871304:
                                    ToastUtils.show("您的密码错误");
                                    dissmissDialog();
                                    break;
                                case 801004:
                                    //密码错误
                                    ToastUtils.show("您的密码错误");
                                    dissmissDialog();
                                    break;
                                case 801003:
                                    //用户不存在
                                    registim();
                                    break;
                                case 801006:
                                    dissmissDialog();
                                    //账号已被封禁
                                    showSelectDialog("提示", "此账号已被封禁", null, null);
                                    break;
                                default:
                                    registim();
                                    break;
                            }
                        }
                    }
                });
    }

    /***
     * 注册极光im
     */
    private void registim() {
        //确定是了
        RegisterOptionalUserInfo userInfo = new RegisterOptionalUserInfo();
        userInfo.setNickname(user.getData().getName());
        JMessageClient.register(user.getData().getAccess_token(), "asd123", userInfo, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    //成功,调用登录
                    LoginIm();
                } else {
                    switch (i) {
                        case 871305:
                            ToastUtils.show("用户名不能低于4位,请联系管理员重新添加账号");
                            break;
                        default:
                            ToastUtils.show("错误:" + s);
                            break;
                    }
                }
            }
        });
    }

}
